package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.BizTmp;
import cc.rengu.redp.bizimpl.upmp.domain.NuccInstInfo;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpPrivilegeCheck;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.DateUtil;
import cc.rengu.redp.common.utils.SortUtil;
import cc.rengu.redp.bizimpl.upmp.dao.CupsInstInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.CupsInstInfo;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author LiuYuLiang.LL
 */
@Service
@DS("upmp")
public class CupsInstInfoServiceImpl extends ServiceImpl<CupsInstInfoMapper, CupsInstInfo> implements CupsInstInfoService {
    @Autowired
    private IBizTmpService bizTmpService;
    @Autowired
    IUpmpPrivilegeCheckService privilegeCheckService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IBizHisService bizHisService;
    private String oprMenuId = "1";
    private String oprMenuName = "参数管理:银联机构号管理";
    private long chkMenuId = 2;
    private String chkMenuName = "参数管理:银联机构号审核";
    private String webNextUrl = "";

    @Override
    public IPage<CupsInstInfo> findByPage(QueryRequest request, CupsInstInfo info) {
        try {
            LambdaQueryWrapper<CupsInstInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(info.getCrtOrgId())) {
                queryWrapper.like(CupsInstInfo::getCrtOrgId, info.getCrtOrgId());
            }
            if (StringUtils.isNotBlank(info.getCupsInstName())) {
                queryWrapper.like(CupsInstInfo::getCupsInstName, info.getCupsInstName());
            }
            Page<CupsInstInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            return this.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("查询失败", e);
            return null;
        }
    }

    @Override
    @Transactional
    public void create(CupsInstInfo entity) throws RedpException {
        // 获取当前登录用户信息
        UpmpUserInfoVO user= CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt =  DateUtil.getDateFormat(new Date(),DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
      entity.setOprId(user.getId());
        entity.setCrtOrgId(user.getOrgCode());
        entity.setCreateTime(lastUpddt);
         entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);
        if(StringUtils.isBlank(entity.getCupsInstLevel()))entity.setCupsInstLevel("00");
        //检查新增操作是否需要审核，我们是保存在权限审核配置表中，新的表结构是  T_B_PRIVILEGE_CHECK
        UpmpPrivilegeCheck privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "参数管理:银联机构号管理:增加");
        if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
            //需要审核，状态为草稿，审核状态为审核中
            entity.setCupsInstStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType());
            this.baseMapper.insert(entity);
            //临时数据表数据插入-待完成
            bizTmpService.saveBizTmp(entity, user,user.getInstId(), BizOprEnum.OPR_ADD.getType(),DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN)
                    , oprMenuId, oprMenuName, entity.getCupsInstStatus(), entity.getAuditStatus(), String.valueOf(entity.getId()), webNextUrl, null, null, null);

        } else {
            //无需审核，状态为正式，审核状态为审批通过
            entity.setCupsInstStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
            this.baseMapper.insert(entity);
            bizHisService.saveBizHisNew(entity, entity, user, user.getInstId(), BizOprEnum.OPR_ADD.getType(),DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN)
                    , oprMenuId, oprMenuName, String.valueOf(entity.getId()), null, null, null);
        }

    }

    @Override
    @Transactional
    public void update(CupsInstInfo entity) throws RedpException {
        // 获取当前登录用户信息
        UpmpUserInfoVO user= CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt =  DateUtil.getDateFormat(new Date(),DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
        CupsInstInfo cupsInstInfo = new CupsInstInfo();
        BeanUtils.copyProperties(entity, cupsInstInfo);
        CupsInstInfo dbCupsInstInfo = this.getById(entity.getId());

        UpmpPrivilegeCheck privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "参数管理:银联机构号管理:修改");
        if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
            cupsInstInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
            dbCupsInstInfo.setLastOprId(user.getOrgCode());
            cupsInstInfo.setLastUpdateTime(lastUpddt);

            this.baseMapper.updateById(cupsInstInfo);

            //检查临时表是否有数据，如果没用则新增
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType());
            cupsInstInfo = new CupsInstInfo();
            BeanUtils.copyProperties(entity, cupsInstInfo);

            bizTmpService.saveBizTmp(cupsInstInfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(),DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN)
                    , oprMenuId, oprMenuName, cupsInstInfo.getCupsInstStatus(), cupsInstInfo.getAuditStatus(), String.valueOf(cupsInstInfo.getId()), webNextUrl, null, null, null);

        } else {
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
            entity.setLastOprId(user.getId());
            entity.setLastUpdateTime(lastUpddt);
            BeanUtils.copyProperties(entity, cupsInstInfo);
            this.baseMapper.updateById(cupsInstInfo);

            //历史表新增
            bizHisService.saveBizHisNew(cupsInstInfo, dbCupsInstInfo, user, user.getInstId(), BizOprEnum.OPR_UPDATE.getType(),DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN)
                    , oprMenuId, oprMenuName, String.valueOf(cupsInstInfo.getId()), null, null, null);
        }
    }

    @Override
    @Transactional
    //审核
    public void audit(CupsInstInfo entity, String opt, String approvalRefuseReason) throws RedpException {
        // 获取当前登录用户信息
        UpmpUserInfoVO user= CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt =  DateUtil.getDateFormat(new Date(),DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
        //获取临时表数据并转换成实体对象
        BizTmp tmp = bizTmpService.getBizTmpDetail(entity.getId());
        if (tmp != null) {
            log.error("根据id没有找到指定临时表数据！");
            throw new RedpException("根据id没有找到指定临时表数据！");
        }
        String bizdata = "";
        if (null != tmp.getBizData1()) {
            bizdata += tmp.getBizData1();
        }
        if (null != tmp.getBizData2()) {
            bizdata += tmp.getBizData2();
        }
        if (null != tmp.getBizData3()) {
            bizdata += tmp.getBizData3();
        }
        // 临时表数据
        CupsInstInfo cupsInstInfoNew = JSON.parseObject(bizdata, CupsInstInfo.class);
        // 正式表数据
        CupsInstInfo cupsInstInfo = this.getById(entity.getId());
        // 备份正式表数据
        CupsInstInfo cupsInstInfoOld = new CupsInstInfo();
        BeanUtils.copyProperties(cupsInstInfo, cupsInstInfoOld);
        //
        if (cupsInstInfo != null && !BizOprEnum.OPR_ADD.equals(tmp.getBizOpr())) {
            log.error("根据id没有找到指定数据！");
            throw new RedpException("根据id没有找到指定数据！");
        }
        if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
            // 审批通过将临时表数据更新到正式表
            BeanUtils.copyProperties(cupsInstInfoNew, cupsInstInfo);
        } else {
            cupsInstInfo.setAuditRefuseReason(approvalRefuseReason);
        }
        String bizOpr = "";
        if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(cupsInstInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                cupsInstInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                cupsInstInfo.setCupsInstStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            } else {
                cupsInstInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_ADD.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType().equals(cupsInstInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                cupsInstInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                cupsInstInfo.setCupsInstStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
            } else {
                cupsInstInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_CANCEL.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType().equals(cupsInstInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                cupsInstInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                cupsInstInfo.setCupsInstStatus(BizDataStatusEnum.STATUS_STOPED.getType());
            } else {
                cupsInstInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_STOP.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType().equals(cupsInstInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                cupsInstInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                cupsInstInfo.setCupsInstStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            } else {
                cupsInstInfo.setCupsInstStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_USE.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(cupsInstInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                cupsInstInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                cupsInstInfo.setCupsInstStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            } else {
                cupsInstInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_UPDATE.getType();
        }
        // 状态赋值完成后，入库正式表
        this.baseMapper.insert(cupsInstInfo);
        //
        if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
            //审批通过将正式表更新到历史表
            bizHisService.saveBizHisNew(cupsInstInfo, cupsInstInfoOld, user, user.getInstId(), bizOpr,DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN), oprMenuId, chkMenuName, String.valueOf(cupsInstInfo.getId()), null, null, null);
        }
        // 修改临时表的审核状态等字段
        bizTmpService.saveBizTmp(cupsInstInfo, user,  user.getInstId(), bizOpr,DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN), oprMenuId, chkMenuName, cupsInstInfo.getCupsInstStatus(), cupsInstInfo.getAuditStatus(), String.valueOf(cupsInstInfo.getId()), webNextUrl, null, null, null);
    }

    @Override
    @Transactional
    public void cancel(String id) throws RedpException {
        CupsInstInfo dbCupsInstInfo = this.getById(id);
        UpmpUserInfoVO user= CommonUtils.getCurrentUser(upmpSysParamService);
        // 注销
        String lastUpddt =  DateUtil.getDateFormat(new Date(),DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN);
        CupsInstInfo entity = this.getById(id);
        entity.setLastOprId(user.getId());
        UpmpPrivilegeCheck privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "参数管理:银联机构号管理:注销");
        String bizOpr = BizOprEnum.OPR_CANCEL.getType();
        entity.setCupsInstStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
        entity.setLastUpdateTime(lastUpddt);
        if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());
            this.baseMapper.updateById(entity);
            //检查临时表是否有数据，如果没用则新增
            bizTmpService.saveBizTmp(entity, user, user.getInstId(), bizOpr,DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN)
                    , oprMenuId, oprMenuName, entity.getCupsInstStatus(), entity.getAuditStatus(), String.valueOf(entity.getId()), webNextUrl, null, null, null);
        } else {
            entity.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
            this.baseMapper.updateById(entity);
            //历史表新增
            bizHisService.saveBizHisNew(entity, dbCupsInstInfo, user, user.getInstId(), bizOpr,DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN)
                    , oprMenuId, oprMenuName, String.valueOf(entity.getId()), null, null, null);

        }
    }

    @Override
    @Transactional
    public void delete(String[] ids) {
        List<String> list = Arrays.asList(ids);
        this.baseMapper.deleteBatchIds(list);
    }

    @Override
    public Map<String, Object> select2(String q, QueryRequest request) {

        if (null == q) {
            return null;
        }
        q = q.replaceAll("&amp;", "&");

        String brandCodeOrName = "";
        String[] param = q.split("&");
        if (null != param && param.length > 0) {
            brandCodeOrName = param[0];
        }

        try {
            LambdaQueryWrapper<CupsInstInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CupsInstInfo::getCupsInstStatus, "01");

            if (StringUtils.isNotEmpty(brandCodeOrName)) {
                String finalbrandCodeOrName = brandCodeOrName;
                queryWrapper.and(qw -> qw.likeRight(CupsInstInfo::getCupsInstId, finalbrandCodeOrName).or().likeRight(CupsInstInfo::getCupsInstName, finalbrandCodeOrName));
            }

            Page<CupsInstInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            Page<CupsInstInfo> page1 = this.page(page, queryWrapper);
            List<CupsInstInfo> listx = page1.getRecords();
            Map<String, Object> maps = new HashMap<String, Object>();
            Map<String, String> map = new HashMap<String, String>();
            List<Object> list = new ArrayList<Object>();
            if (listx != null) {
                for (int i = 0; i < listx.size(); i++) {
                    CupsInstInfo org = listx.get(i);
                    map = new HashMap<String, String>();
                    map.put("id", org.getCupsInstId());
                    map.put("name", org.getCupsInstName());

                    list.add(map);
                }
                maps.put("results", list);
                maps.put("total", page.getTotal());
                int pageIndex = Common.isBlank(request.getPageNum()) ? 1 : request.getPageNum();
                if (pageIndex == page1.getTotal()) {
                    maps.put("more", false);
                } else {
                    maps.put("more", true);
                }
            }
            return maps;

        } catch (Exception e) {
            log.error("获取银联机构号信息失败", e);
            return null;
        }
    }
}
